package com.ikonke.iot.alarm.es;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;

import static com.ikonke.iot.alarm.es.EsRepository.ES_DATE_FORMAT;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 9:40 2020/6/8
 * @Modified By:
 */
@Slf4j
public class GetDocumentDemo {

    public static void main(String[] args) {
      /*  // 指定index
        SearchRequest searchRequest = new SearchRequest("filebeat*");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 多条件查询
        searchSourceBuilder.query(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("message", "Exception"))
                .must(QueryBuilders.termQuery("log_level", "ERROR"))
                .must(QueryBuilders.rangeQuery("timestamp").from(DateUtil.lastWeek().toString(ES_DATE_FORMAT))))
                .sort(SortBuilders.fieldSort("timestamp").order(SortOrder.DESC))
                .from(0)
                .size(10000);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try (RestHighLevelClient client = EsClient.getEsClient()) {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.warn("查询es数据失败", e);
        }
        // 获取命中次数，查询结果有多少对象
        SearchHits hits = searchResponse.getHits();
        log.info("查询结果有：" + hits.getTotalHits() + "条");
        if (null != hits.getHits() && hits.getHits().length > 0) {
            SearchHit hitsHit = hits.getHits()[0];
            log.info("log_level : " + hitsHit.getSourceAsMap().get("log_level"));
            String timestamp = (String) hitsHit.getSourceAsMap().get("timestamp");
            log.info("timestamp : " + timestamp);
            String message = (String) hitsHit.getSourceAsMap().get("message");
            log.info("message : " + message);
            LocalDateTime localDateTime = LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern(ES_DATE_FORMAT));
            // 暂且认为到这块就算已处理
            String tid = (String) hitsHit.getSourceAsMap().get("tid");

        }*/
    }

}
